package com.example.picture_switch;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends AppCompatActivity {
    private ImageView imgDog;
    private Button btnNext;
    private int[] dogimgs = {R.drawable.dog1, R.drawable.dog2,
            R.drawable.dog3, R.drawable.dog4, R.drawable.dog5};
    private int index = 0;
    private Handler handler;
    private final int CHANGE_DOG = 1001;
    private boolean isPause = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imgDog= findViewById(R.id.img_Dog);
        btnNext = findViewById(R.id.btn_Next);

        // CTRL+SHIFT+空格
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                // handler在初始化时就准备好响应ChangeDOG消息
                if(msg.what ==  CHANGE_DOG){
                    index = (index + 1) % dogimgs.length;
                    imgDog.setImageResource(dogimgs[index]);
                    return true;
                }
                return false;
            }
        });

        // 改用线程  自动切换
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // 不能在子线程中修改主线程创建的view
                    // ①创建一个消息并且通过handler发送到主线程
                    if(!isPause){
                        Message message = new Message();
                        message.what = CHANGE_DOG;
                        handler.sendMessage(message);
                    }
                }
            }
        }).start();


        // new 后面的快捷键 CTRL+SHIFT+空格
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isPause = !isPause;
            }
        });
    }
}
